/*
 * @Author: yan_hai_dong 891236760@qq.com
 * @Date: 2022-10-24 13:31:01
 * @LastEditors: yan_hai_dong 891236760@qq.com
 * @LastEditTime: 2022-10-24 17:25:57
 * @FilePath: \app\src\views\canvas\circle\ratio\js\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import Base from "../../js/base.js"
export default class Ratio extends Base {
    constructor(cvs) {
        super(cvs)
        let {
            ctx,
            bl
        } = this
        ctx.lineWidth = 20 * bl
        ctx.lineCap = 'round'
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'

    }
    init(data) {
        let sum = data.reduce((a, b) => a + b.rate, 0)
        data.forEach(v => {
            v.runRate = 10
            v.step = v.rate / sum
        })
        this.data = data
        this.render()
    }
    render() {
        let {
            ctx,
            data,
            cvs,
            lineHeight
        } = this
        ctx.clearRect(0, 0, ctx.width, ctx.height)

        const r = cvs.width / 2

        ctx.beginPath()
        ctx.strokeStyle = '#eeeeee'
        const mt = ctx.lineWidth / 2
        ctx.arc(r, r, r - mt, 0, Math.PI / 180 * 360)
        ctx.stroke()

        data.forEach((v, i) => {
            ctx.beginPath()
            ctx.strokeStyle = v.color
            const start = data.slice(0, i).reduce((a, b) => a + b.step, 0)
            ctx.arc(r, r, r - mt, Math.PI / 180 * (360 * start), Math.PI / 180 * (360 * (v.runRate / 100 + start)))
            ctx.stroke()
            if (v.runRate > v.step * 100) {
                v.runRate = v.step * 100
            } else if (v.runRate < v.step * 100) {
                v.runRate += v.step
            }

            ctx.fillStyle = v.color
            ctx.fillText(`${v.text}: ${(v.step*100).toFixed(0)}%`, cvs.width / 2, i * lineHeight + (cvs.height - lineHeight * data.length) / 2 + lineHeight / 2)
        })
        requestAnimationFrame(this.render.bind(this))
    }
}